//===================================================用户登录判断=======================================================
if(!$.cookie("MYID")){
    var returnurl=encodeURIComponent("http://www.pulu.com/weixin/addnewfriends.html"); //同意后跳转页面
    if(is_weixn()){
        //先微信验证获取openid 如果已经授权过了 直接页面截取openid 然后发送请求获取 用户的ID
        var reg=new RegExp("code=[a-zA-Z0-9]*");
        if(window.location.href.match(reg)&&$.cookie("wx")=="over"){
            var code=window.location.href.match(reg);
            $.ajax({
                type:"GET",
                url:"GetOpenId.ashx?"+code,
                async: false,
                success:function(data){
                    var dat=data;
                    $.cookie("wxod",dat);
                    $.cookie("wxopenid",dat);
                    //发请求获取用户的id
                    $.ajax({
                        type:"GET",
                        url:getwxopenidurl+dat,
                        success:function(d){
                            //如果没有用户id 则证明用户是第一次登陆 保存openid跳转至登录页面
                            if(!d.Data||!d.Data.userId){
                                //微信跳转进来的
                                if(!$.cookie("MYID")||$.cookie("MYID").length<10){
                                    $.cookie("wxopenid",dat);
                                    location.href="http://www.pulu.com/weixin/login.html"
                                }
                                //退出登录的
                            }else if(d.Data&&d.Data.userId.length>0){
                                $.cookie("wxopenid",d.Data.openId);
                                $.cookie("MYID",d.Data.userId);
                                $.cookie("MYAVA",d.Data.userAva);
                                $.cookie("MYNICK",d.Data.userNick);
                                location.href="http://www.pulu.com/weixin/addnewfriends.html";
                            }
                        }
                    })
                }
            })
        }
        else{
            $.cookie("wx","over");
            location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx658c34793ecfd9f9&redirect_uri="+returnurl+"&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
        }
    }
    else{
        location.href="login.html";
    }
}
//===================================================获取用户ID=========================================================
var id="";
if($.cookie("MYID")){id=$.cookie("MYID")};
var nick="";//搜索内容

//    监听输入框状态
$(function(){
    $("#searchip").bind('input propertychange', function() {

        $("#newsplace").css("display","block");
        $("#searchlidt").css("display","none");
    });
});
if($("#searchip").val()&&!$("#searchip").val().match(/^\s+$/g)){ //.match(/^\s+$/g)
    console.log($("#searchip").val());
    nick=$("#searchip").val().replace(/\s/g,"");
    searchf();
}
//===================================================昵称搜索好友=======================================================
var canClick=true;//能点
function searchf(){
    if(canClick){
        canClick=false;
        $.ajax({
            datatype:"json",
            type:"get",
            url:searchfriendurl+"?userId="+id+"&nick="+nick,
            success:function(data){
                canClick=true;
                //$(".myinfor").css("display","none");
                $("#newsplace").css("display","none");
                $("#searchlidt").css("display","block");
                $("#searchtitlenum").html(data.Data.length);
                if(data.Data&&data.Data.length>0){
                    for(var i=0;i<data.Data.length;i++){
                        var job="";
                        data.Data[i].index=i;
                        var reg=/([A-Za-z0-9\u4E00-\u9FA5])*/;
                        if(data.Data[i].jobs&&data.Data[i].jobs.length>0){
                            jobname=data.Data[i].jobs[0].typename;
                        }else if(data.Data[i].hobbys&&data.Data[i].hobbys.length>0){
                            jobname=data.Data[i].hobbys[0].typename;
                        }else{
                            jobname="";
                        }
                        var headimg="<img src='img/af8.png' class='topic_photo_img'/>";
                        if(data.Data[i].headimg){
                            headimg="<img src='"+imgurl+data.Data[i].headimg+"' class='topic_photo_img'/>";
                        }
                        var thisRealNick="";
                        if(data.Data[i].realName){thisRealNick=" ("+data.Data[i].realName+")"};
                        $("#searchlidt").append("<div class='ts_cells'><a href='otherpeoplepage.html?otherid="+data.Data[i].userId+"'><div class='Cell'> <div class='tc_image userimgbox'>"+headimg+"</div><div class='newsplaceright'><div class='title'>"+data.Data[i].nick+thisRealNick+" </div><div class='words'>"+job+"</div></div></div></a></div>");
                    }
                    //调整图片区域大小
                    $(".userimgbox").height($(".userimgbox").eq(0).width());
                    var wid=document.getElementsByClassName("userimgbox")[0].style.width;
                    console.log(wid);
                };
            }
        });
    }
}
document.onkeydown=function(event){
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if(e && e.keyCode==13&&canClick){ // enter 键
        $("#searchlidt div.ts_cells").remove();
        if($("#searchip").val()&&!$("#searchip").val().match(/^\s+$/g)){ //.match(/^\s+$/g)
            console.log($("#searchip").val());
            nick=$("#searchip").val().replace(/\s/g,"");
            searchf();
        }
    }
};
$("#serachbtn").click(function(){
    if(canClick){
        $("#searchlidt div.ts_cells").remove();
        if($("#searchip").val()&&!$("#searchip").val().match(/^\s+$/g)){ //.match(/^\s+$/g)
            console.log($("#searchip").val());
            nick=$("#searchip").val().replace(/\s/g,"");
            searchf();
        }
    }
});
//===================================================微信扫一扫=========================================================
//$.ajax({
//    type:"GET",
//    url:"GetSign.ashx?p=weixin/addnewfriends.html",
//    success:function(data){
//        timestampone=data.timestamp;
//        nonceStrone=data.nonceStr;
//        signatureone=data.signature;
//        wx.config({
//            debug: false,
//            appId: 'wx658c34793ecfd9f9',
//            timestamp:timestampone, //时间戳
//            nonceStr:nonceStrone,  //随机字符串
//            signature:signatureone,  //SHA1编码
//            jsApiList: [
//                // 所有要调用的 API 都要加到这个列表中
//                "scanQRCode"
//            ]
//        });
//    }
//});
//$("#wxsaoyisao").click(function(){
//    wx.scanQRCode({
//        needResult: 0, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
//        scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码，默认二者都有
//        success: function (res) {
//            var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
//        }
//    });
//});
//===================================================添加好友=========================================================
//函数列队执行--------------------------------------
var stack=[];//保存执行函数数组
var messarrid=[];//保存信息 ↑stack中函数使用
//编写函数列队方法 next();
function next(){
    //执行最靠前的一个
    var fn=stack[0];
    if(typeof fn==="function")fn(messarrid[0]);
}
//===================================================好友添加删除=======================================================
var friendMessageNum=0;//好友信息的数量 用于控制cookie数值 显示红点
$().ready(function(){
    //环信建立连接
    var conn = new WebIM.connection({
        https: WebIM.config.https,
        url: WebIM.config.xmppURL,
        isAutoLogin: WebIM.config.isAutoLogin,
        isMultiLoginSessions: WebIM.config.isMultiLoginSessions
    });
//登录
    var options = {
        apiUrl: WebIM.config.apiURL,
        user:id,
        pwd:id,
        appKey: "pulu#pulu"
    };
    conn.open(options);

    //获取申请列表
    $.ajax({
        datatype:"json",
        type:"get",
        url:getfriendnoteurl+id,
        success:function(d){
            if(d.Data&&d.Data.length>0){
                friendMessageNum=d.Data.length;
                $.cookie("friendMsgNum",friendMessageNum);//当前红点
                $("#newsplace").css("display","block");
                for(var i=0;i< d.Data.length;i++){
                    var avaimg="<img src='img/af8.png' class='topic_photo_img'>";
                    if(d.Data[i].headImg){
                        avaimg="<img src='"+imgurl+d.Data[i].headImg+"' class='topic_photo_img'>";
                    }
                    var msg="请求添加你为朋友";
                    if(d.Data[i].msg){
                        if(d.Data[i].msg==="[resp:true]"){
                            d.Data[i].msg=d.Data[i].nick+"申请添加你为好友";
                        }
                        msg=d.Data[i].msg;
                        if($.cookie("MYNICK")){
                            var wrongmsg=$.cookie("MYNICK")+"申请添加好友";
                            if(wrongmsg==d.Data[i].msg){
                                msg=d.Data[i].nick+"申请添加你为好友";
                            }
                        }
                    }
                    if(d.Data[i].status==1){
                        $("#newsplace").append("<div class='friends' id='fridiv"+d.Data[i].id+"'><div class='imageplace'><a href='otherpeoplepage.html?otherid="+d.Data[i].userId+"'>"+avaimg+"</a></div><div class='addfribtn' id='addfriend"+d.Data[i].id+"'  data-id="+d.Data[i].id+" data-fid='"+d.Data[i].userId+"'>接受</div><div class='delfribtn' id='del"+d.Data[i].id+"'  data-id="+d.Data[i].id+" data-fid='"+d.Data[i].userId+"'>拒绝</div><div class='haveadd' id='haveadd"+d.Data[i].id+"' style='display:none'>已添加</div><div class='innerplace'><span class='tc_text'>"+d.Data[i].nick+"</span><p>"+msg+"</p></div></div>");
                    }
                    else if(d.Data[i].status==2){
                        $("#newsplace").append("<div class='friends' id='fridiv"+d.Data[i].id+"'><div class='imageplace'><a href='otherpeoplepage.html?otherid="+d.Data[i].userId+"'>"+avaimg+"</a></div><div class='addfribtn' id='addfriend"+d.Data[i].id+"'  data-id="+d.Data[i].id+" data-fid='"+d.Data[i].userId+"' style='display:none'>接受</div><div class='haveadd' id='haveadd"+d.Data[i].id+"' style='display:block'>已添加</div><div class='innerplace'><span class='tc_text'>"+d.Data[i].nick+"</span><p>"+msg+"</p></div></div>");
                    }
                }
                if($("#searchip").val().length>0){
                    $("#newsplace").css("display","none");
                }
            }else{
                $("#newsplace").remove();
            }
        }

    });
    //同意好友
    $("#newsplace").delegate(".addfribtn","click",function(e){
        console.log(e.target.dataset.fid);
        var fromuserid= e.target.dataset.fid;
        var noteid=e.target.dataset.id;
        //------------------------------------------
        conn.subscribed({
            to:fromuserid,
            status:"[resp:true]",
            message : '[resp:true]'
        });
        conn.subscribe({//需要反向添加对方好友
            to:fromuserid,
            status:"[resp:true]",
            message : '[resp:true]'
        });
        //-------原---------------------------
        //conn.subscribed({
        //    to:id,
        //    status:"[resp:true]"
        //    //message :"[resp:true]"
        //    //message :"同意添加"
        //});
        //关闭提示框  id userId friendId status
        $.ajax({
            type:"post",
            datatype:"json",
            url:"https://www.pulu.com/webapi/api/PuluGoodFriend/Addpulu_goodfriend",
            data:{"userId":id,"friendId":fromuserid},
            success:function(d){
                $("#haveadd"+noteid).css("display","block");
                $("#addfriend"+noteid).css("display","none");
                $("#del"+noteid).css("display","none");
                //$.ajax({
                //    type:"post",
                //    datatype:"json",
                //    url:updatefriendnoteurl,
                //    data:{"id":noteid,"userId":id,"friendId":fromuserid,"status":2},
                //    success:function(d){
                //        console.log();
                //    }
                //})
            }
        });
        friendMessageNum--;
        $.cookie("friendMsgNum",friendMessageNum);//当前红点
        $.cookie("changeFMN","changed");//已经处理好友申请了
    });
    //拒绝好友
    $("#newsplace").delegate(".delfribtn","click",function(e){
        console.log(e.target.dataset.fid);
        var fromuserid= e.target.dataset.fid;
        var noteid=e.target.dataset.id;
        conn.unsubscribed({
            to:fromuserid,
            message : "拒绝"
        });
        //关闭提示框
        $.ajax({
            type:"post",
            datatype:"json",
            url:"https://www.pulu.com/webapi/api/PuluFriendMsg/RefuseFriend",
            data:{"userId":id,"friendId":fromuserid},
            success:function(d){
                $("#fridiv"+noteid).remove();
                if(!document.querySelectorAll("#fridiv .friends")[0]){
                    $("#newsplacetitle").css("display","none");
                }
            }
        });
        friendMessageNum--;
        $.cookie("friendMsgNum",friendMessageNum);//当前红点
        $.cookie("changeFMN","changed");//已经处理好友申请了
    });
    conn.listen({
        //事件监听（加好友通知）
        onPresence: function ( e ) {
            console.log(e);
            //只处理好友申请
            if ( e.type === 'subscribe'&&(e.status!="[resp:true]") ){
                //处理信息数据格式 方便调用
                var mes={"type":e.type,"from":e.from,"status":e.status};
                //将信息插入到数组中 进行保存
                messarrid.push(mes);
                //服务器传递数据
                function sendfriendnot(e){
                    if ( e.type === 'subscribe' ){
                        $.ajax({
                            type:"post",
                            url:savefriendnoteurl,
                            data:{"userId":id,"friendId":e.from,"msg":e.status},
                            success:function(d){
                                stack.shift();
                                messarrid.shift();
                                next();
                            }
                        });
                    }
                }
                //将方法插入到数组中 列队执行
                //stack.push(handlePresence);
                stack.push(sendfriendnot);
                //执行next()
                next();
            }
        },
        //收到联系人订阅请求、处理群组、聊天室被踢解散等消息
        onOpened: function ( message ) {
            conn.setPresence();
            conn.getRoster({
                success: function ( roster ) {
                    for ( var i = 0, l = roster.length; i < l; i++ ) {
                        var ros = roster[i];
                        //ros.subscription值为both/to为要显示的联系人，此处与APP需保持一致，才能保证两个客户端登录后的好友列表一致
                        if ( ros.subscription === 'both' || ros.subscription === 'to' ) {
                            //console.log(ros);
                        }
                    }
                },
                error:function(d){
                    console.log(d);
                }
            });
            //console.log("结束调用好友列表");
        }
    });
});
//=========================================================返回按钮=====================================================
document.getElementsByClassName("mweb_modal_back_button")[0].onclick=function(){
    if(/addnewfriends/.test(document.referrer)||!document.referrer){
        location.href="pulu.html"
    }else{
        history.go(-1);
    }
};
//===================================================返回去除好友通知红点===============================================
$.cookie("comefrom","addnewfriends");